<template>
	<a-card :bordered="false">
		<a-form ref="searchFormRef" name="advanced_search" :model="searchFormState" class="ant-advanced-search-form">
			<a-row :gutter="24">
				<a-col :span="5">
					<a-form-item label="资产分类" name="assetCategory">
						<a-select
							v-model:value="searchFormState.assetCategory"
							placeholder="请选择资产分类"
							:options="assetsCategoryOptions"
							allowClear
						/>
					</a-form-item>
				</a-col>
				<a-col :span="5">
					<a-form-item label="资产状态" name="assetStatus">
						<a-select
							v-model:value="searchFormState.assetStatus"
							placeholder="请选择资产状态"
							:options="assetsStatusOptions"
							allowClear
						/>
					</a-form-item>
				</a-col>
				<a-col :span="5">
					<a-form-item label="资产名称" name="assetName">
						<a-input v-model:value="searchFormState.assetName" placeholder="请输入资产名称" />
					</a-form-item>
				</a-col>
				<a-col :span="5">
					<a-form-item label="资产编码" name="assetCode">
						<a-input v-model:value="searchFormState.assetCode" placeholder="请输入资产编码" />
					</a-form-item>
				</a-col>
				<a-col :span="4">
					<a-button type="primary" @click="refreshParentAndCollapseAll">查询</a-button>
					<a-button style="margin: 0 8px" @click="reset">重置</a-button>
				</a-col>
			</a-row>
		</a-form>
		<s-table
			ref="parentTableRef"
			:columns="parentColumns"
			:data="loadParentData"
			bordered
			rowKey="assetCategory"
			:expand-row-by-click="true"
			:expanded-row-keys="expandedRowKeys"
			@onExpand="handleParentExpand"
		>
			<template #operator class="table-operator">
				<a-space>
					<a-button type="primary" @click="formRef.onOpen()" v-if="hasPerm('bizNoticeAdd')">
						<template #icon>
							<plus-outlined />
						</template>
						新增
					</a-button>
					<a-button type="primary" @click="importRef.onOpen()" v-if="hasPerm('bizNoticeAdd')">
						<template #icon>
							<UploadOutlined />
						</template>
						导入
					</a-button>
				</a-space>
			</template>
			<template #expandedRowRender="{ record: parentRecord }">
				<a-table
					:columns="childColumns"
					:data-source="childData[parentRecord.assetCategory] || []"
					:pagination="childPagination[parentRecord.assetCategory]"
					:loading="childLoading[parentRecord.assetCategory]"
					rowKey="id"
					bordered
					size="small"
					:scroll="{ x: 'max-content' }"
					@change="(pagination) => handleChildTableChange(parentRecord.assetCategory, pagination)"
				>
					<template #bodyCell="{ column, record: childRecord }">
						<template v-if="column.dataIndex === 'image'">
							<div v-if="childRecord.image && childRecord.image !== ''" class="image-cell">
								<a-image
									:src="jdOssBaseUrl + childRecord.image"
									:width="50"
									:height="50"
									:preview="{
										visible: previewVisible.image === childRecord.id,
										onVisibleChange: (visible) => handlePreviewVisibleChange(visible, 'image', childRecord.id)
									}"
								/>
							</div>
						</template>
						<template v-if="column.dataIndex === 'action'">
							<a-space>
								<a-button
									type="link"
									v-if="childRecord.assetStatus === 0"
									@click="operationModelRef?.show(childRecord.id, 5, '资产维修')"
									>维修
								</a-button>
								<a-button
									type="link"
									v-if="childRecord.assetStatus === 0"
									@click="operationModelRef?.show(childRecord.id, 8, '资产调拨')"
									>调拨
								</a-button>
								<a-button type="link" @click="formRef.onOpen(childRecord)">编辑</a-button>
								<a-button type="link" @click="historyRef.onOpen(childRecord.id)">历史</a-button>
								<!--								<a-divider type="vertical"/>-->
								<!--								<a-popconfirm v-if="childRecord.assetStatus===0" title="确定要删除此资产吗？"-->
								<!--											  @confirm="deleteModule(childRecord)">-->
								<!--									<a-button type="link" danger size="small">删除</a-button>-->
								<!--								</a-popconfirm>-->
							</a-space>
						</template>
					</template>
				</a-table>
			</template>
		</s-table>
	</a-card>
	<EditForm ref="formRef" @successful="handleFormSuccess" />
	<Import ref="importRef" />
	<History ref="historyRef" />
	<OperationModel ref="operationModelRef" @confirm="handleFormSuccess" />
</template>

<script setup name="AssetsAdmin">
	import assetsAdminApi from '@/api/hrms/assets/admin/assetsAdminApi'
	import EditForm from '@/views/hrms/assets/admin/form.vue'
	import tool from '@/utils/tool'
	import History from '@/views/hrms/assets/admin/history.vue'
	import OperationModel from '@/views/hrms/assets/admin/operationModel.vue'
	import Import from '@/views/hrms/assets/admin/import.vue'

	const searchFormState = ref({
		current: 1,
		size: 10
	})
	const parentTableRef = ref()
	const searchFormRef = ref()
	const formRef = ref()
	const importRef = ref()
	const operationModelRef = ref()
	const historyRef = ref()
	const childData = ref({})
	const childLoading = ref({})
	const childPagination = ref({})
	const expandedRowKeys = ref([])
	const jdOssBaseUrl = 'https://s3.cn-north-1.jdcloud-oss.com/'
	const assetsCategoryOptions = tool.dictList('ASSETS_CATEGORY')
	const assetsStatusOptions = tool.dictList('ASSETS_STATUS')
	const parentColumns = [
		{ title: '资产分类', dataIndex: 'assetCategoryName' },
		{ title: '总数量', dataIndex: 'totalCount' },
		{ title: '可领用', dataIndex: 'noUse' },
		{ title: '已领用', dataIndex: 'inUse' },
		{ title: '报修中', dataIndex: 'underRepair' },
		{ title: '已报废', dataIndex: 'discarded' },
		{ title: '调拨中', dataIndex: 'allocating' },
		{ title: '已出库', dataIndex: 'shipped' }
	]
	const previewVisible = ref({
		image: null,
		signatureImg: null
	})
	const childColumns = [
		{ title: '', dataIndex: 'image', align: 'center', width: 150 },
		{ title: '资产名称', dataIndex: 'assetName' },
		{ title: '资产状态', dataIndex: 'assetStatusName' },
		{ title: '资产编号', dataIndex: 'assetCode' },
		{ title: '规格', dataIndex: 'specification' },
		{ title: '序列号', dataIndex: 'serialNumber' },
		{ title: '操作', dataIndex: 'action', align: 'center', width: 200 }
	]

	// 加载父级数据
	const loadParentData = async (params) => {
		return assetsAdminApi.outerPage(searchFormState.value).then((res) => {
			return res
		})
	}

	const handleParentExpand = (expanded, record) => {
		if (expanded) {
			expandedRowKeys.value = [...expandedRowKeys.value, record.assetCategory]
			loadChildData(record.assetCategory, 1, 5)
		} else {
			expandedRowKeys.value = expandedRowKeys.value.filter((key) => key !== record.assetCategory)
		}
	}

	const loadChildData = async (assetCategory, current, size) => {
		try {
			const res = await assetsAdminApi.pageList({
				...searchFormState.value,
				current: current,
				size: size
			})
			childData.value[assetCategory] = res.records || []
			childPagination.value[assetCategory] = {
				...childPagination.value[assetCategory],
				current: current,
				pageSize: size,
				total: res.total || 0
			}
		} catch (error) {
			console.error('加载子级数据失败:', error)
			childData.value[assetCategory] = []
			childPagination.value[assetCategory] = {
				...childPagination.value[assetCategory],
				current: current,
				pageSize: size,
				total: 0
			}
		}
	}

	const handleChildTableChange = async (assetCategory, pagination) => {
		const { current, pageSize } = pagination
		childLoading.value[assetCategory] = true
		try {
			await loadChildData(assetCategory, current, pageSize)
		} catch (error) {
			console.error('分页加载失败:', error)
		} finally {
			childLoading.value[assetCategory] = false
		}
	}

	const handlePreviewVisibleChange = (visible, type, recordId) => {
		if (visible) {
			previewVisible.value[type] = recordId
		} else {
			previewVisible.value[type] = null
		}
	}

	// 刷新父列表并折叠所有子列表
	const refreshParentAndCollapseAll = () => {
		// 重新查询父列表，关闭所有展开的行
		if (parentTableRef.value) {
			parentTableRef.value.refresh(true)
		}
		// 清空所有子表数据和分页信息，确保展开时重新加载最新数据
		childData.value = {}
		childPagination.value = {}
		childLoading.value = {}
		// 清空展开行keys，确保所有行都折叠
		expandedRowKeys.value = []
	}

	// 重置
	const reset = () => {
		searchFormRef.value.resetFields()
		refreshParentAndCollapseAll()
	}

	// 表单操作成功后的回调
	const handleFormSuccess = () => {
		refreshParentAndCollapseAll()
	}
</script>
